package com.bawei.mall.product.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.*;

import com.alibaba.fastjson.JSON;
import com.bawei.common.core.domain.R;
import com.bawei.common.core.exception.ServiceException;
import com.bawei.common.core.utils.DateUtils;
import com.bawei.common.core.utils.StringUtils;
import com.bawei.common.core.utils.bean.BeanUtils;
import com.bawei.common.core.utils.thread.ThreadPool;
import com.bawei.common.rabbit.domain.Message;
import com.bawei.common.rabbit.enums.QueueEnum;
import com.bawei.common.security.handler.GlobalExceptionHandler;
import com.bawei.common.security.utils.SecurityUtils;
import com.bawei.mall.product.cache.ProductInfoCache;
import com.bawei.mall.product.domain.MallProductRuleInfo;
import com.bawei.mall.product.domain.MallProductSkuInfo;
import com.bawei.mall.product.domain.MallProductTypeInfo;
import com.bawei.mall.product.domain.model.ProductModel;
import com.bawei.mall.product.domain.model.SkuModel;
import com.bawei.mall.product.domain.reponse.ProductDetailsResponse;
import com.bawei.mall.product.domain.reponse.ProductInfoResponse;
import com.bawei.mall.product.domain.request.ProductInfoRequest;
import com.bawei.mall.product.service.IMallProductRuleInfoService;
import com.bawei.mall.product.service.IMallProductSkuInfoService;
import com.bawei.mall.product.mapper.MallProductSkuInfoMapper;
import com.bawei.mall.product.mapper.MallProductTypeInfoMapper;
import com.bawei.mall.product.service.IMallProductRuleInfoService;
import com.bawei.mall.product.service.IMallProductSkuInfoService;
import com.bawei.mall.product.service.IMallProductTypeInfoService;
import com.bawei.mall.product.util.ObjectToMapConverter;
import com.bawei.system.domain.vo.EsDocInsertVo;
import com.bawei.system.remote.api.RemoteEsDocService;
import com.bawei.system.remote.api.RemoteEsIndexService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.bawei.mall.product.mapper.MallProductInfoMapper;
import com.bawei.mall.product.domain.MallProductInfo;
import com.bawei.mall.product.service.IMallProductInfoService;
import org.springframework.transaction.annotation.Transactional;

import org.springframework.util.CollectionUtils;


import javax.annotation.PostConstruct;

/**
 * 商品信息Service业务层处理
 *
 * @author DongZeLiang
 * @date 2022-09-19
 */
@Service
@Slf4j
public class MallProductInfoServiceImpl implements IMallProductInfoService {
    @Autowired
    private MallProductInfoMapper mallProductInfoMapper;

    @Autowired
    private IMallProductSkuInfoService skuInfoService;

    @Autowired
    private IMallProductRuleInfoService ruleInfoService;

    @Autowired
    private MallProductSkuInfoMapper skuInfoMapper;


    @Autowired
    private ProductInfoCache productInfoCache;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private RemoteEsDocService remoteEsDocService;

    @Autowired
    private RemoteEsIndexService remoteEsIndexService;

    @Autowired
    private MallProductTypeInfoMapper mallProductTypeInfoMapper;

    private static final String INDEX_NAME="product_info";

    /**
     * 项目启动时，把商品数据初始化到ES中
     */
    @PostConstruct
    public void init() {
        loadingProductInfoToEs();
    }

    /**
     * 查询商品信息
     *
     * @param id 商品信息主键
     * @return 商品信息
     */
    @Override
    public ProductInfoResponse selectMallProductInfoById(Long id) {
        MallProductInfo mallProductInfo = mallProductInfoMapper.selectMallProductInfoById(id);
        ProductInfoResponse productInfoResponse = new ProductInfoResponse();
        BeanUtils.copyBeanProp(productInfoResponse, mallProductInfo);
        productInfoResponse.setSkuInfoList(
                skuInfoService.selectMallProductSkuInfoList(new MallProductSkuInfo() {{
                    setProductId(id);
                }})
        );
        return productInfoResponse;
    }

    @Override
    public ProductDetailsResponse selectProductDetailsById(Long productId) {
        if (productId == null || productId == 0) {
            throw new ServiceException("查询商品信息，依据不合法！");
        }
        ProductDetailsResponse productDetailsResponse = new ProductDetailsResponse();
        ProductModel productModel = mallProductInfoMapper.selectProductModelById(productId);
        if (productModel == null) {
            throw new ServiceException("查询商品信息，商品数据为空");
        }
        productDetailsResponse.setProduct(productModel);
        List<MallProductSkuInfo> mallProductSkuInfos = skuInfoService.selectMallProductSkuInfoList(productId);
        if (mallProductSkuInfos == null || mallProductSkuInfos.size() == 0) {
            throw new ServiceException("查询商品信息，SKU数据为空");
        }
        productDetailsResponse.setSkuList(mallProductSkuInfos);
        MallProductRuleInfo ruleInfo = ruleInfoService.selectMallProductRuleInfoById(productModel.getRuleId());
        if (ruleInfo == null) {
            throw new ServiceException("查询商品信息，规格数据为空");
        }
        productDetailsResponse.setProductRule(ruleInfo);
        return productDetailsResponse;
    }

    /**
     * 查询商品信息列表
     *
     * @param mallProductInfo 商品信息
     * @return 商品信息
     */
    @Override
    public List<MallProductInfo> selectMallProductInfoList(MallProductInfo mallProductInfo) {
        return mallProductInfoMapper.selectMallProductInfoList(mallProductInfo);
    }

    /**
     * 新增商品信息
     *
     * @param productInfoRequest 商品信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertMallProductInfo(ProductInfoRequest productInfoRequest) {
        productInfoRequest.setCreateBy(String.valueOf(SecurityUtils.getUserId()));
        productInfoRequest.setCreateTime(DateUtils.getNowDate());
        int i = mallProductInfoMapper.insertMallProductInfo(productInfoRequest);
        if (i == 0) {
            return i;
        }

        skuInfoService.batchInsertProductSku(
                SkuModel.builderSkuModel(productInfoRequest.getId(), productInfoRequest.getSkuInfoList())
        );

        // 给搜索系统发送消息需要进行搜索更新
        try {
            rabbitTemplate.convertAndSend(QueueEnum.PRODUCT_ADD.queueName(),
                    Message.builderMsg(productInfoRequest.getId()));
        } catch (ServiceException serviceException) {
            throw new ServiceException("给搜索系统发送消息需要进行搜索更新失败！");
        }
        return i;
    }

    /**
     * 修改商品信息
     *
     * @param productInfoRequest 商品信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateMallProductInfo(ProductInfoRequest productInfoRequest) {
        productInfoRequest.setUpdateBy(String.valueOf(SecurityUtils.getUserId()));
        productInfoRequest.setUpdateTime(DateUtils.getNowDate());
        int i = mallProductInfoMapper.updateMallProductInfo(productInfoRequest);
        if (i == 0) {
            //将商品信息推送至MQ，异步更新ES
            try {
                rabbitTemplate.convertAndSend(QueueEnum.PRODUCT_ADD.queueName(),
                        Message.builderMsg(productInfoRequest.getId()));
            } catch (ServiceException serviceException) {
                throw new ServiceException("给搜索系统发送消息需要进行搜索更新失败！");
            }
            return i;
        }
        skuInfoService.deleteMallProductSkuInfoByProductId(productInfoRequest.getId());
        skuInfoService.batchInsertProductSku(
                SkuModel.builderSkuModel(productInfoRequest.getId(), productInfoRequest.getSkuInfoList())
        );
        return i;
    }

    /**
     * 批量删除商品信息
     *
     * @param ids 需要删除的商品信息主键
     * @return 结果
     */
    @Override
    public int deleteMallProductInfoByIds(Long[] ids) {
        skuInfoService.deleteMallProductSkuInfoByProductIds(ids);
        for (Long id : ids) {
            // 延迟执行
            productInfoCache.delayRemove(id);
        }
        return mallProductInfoMapper.deleteMallProductInfoByIds(ids);
    }

    /**
     * 删除商品信息信息
     *
     * @param id 商品信息主键
     * @return 结果
     */
    @Override
    public int deleteMallProductInfoById(Long id) {
        return mallProductInfoMapper.deleteMallProductInfoById(id);
    }

    /**
     * 商品总条数
     *
     * @param mallProductInfo 商品查询
     * @return
     */
    @Override
    public Long selectMallProductInfoCount(MallProductInfo mallProductInfo) {
        return mallProductInfoMapper.selectMallProductInfoCount(mallProductInfo);
    }

    /**
     * 商品上下架
     *
     * @param id
     * @return
     */
    @Override
    public R uploadInfo(Long id) {
        //查询商品信息
        MallProductInfo mallProductInfo = mallProductInfoMapper.selectMallProductInfoById(id);
        if (mallProductInfo == null) {
            throw new ServiceException("商品信息不存在");
        }
        //TODO 调用ES查询商品是否上架
        //feignClient.uploadInfo(id,"index");
        //TODO 查询商品SKU信息

        //TODO 封装ES商品信息
        //TODO 调用ES上架商品
        return R.ok();
    }

    @Override
    public void loadingProductInfoToEs() {
        //查询所有商品信息
        List<MallProductInfo> mallProductInfos = mallProductInfoMapper.selectMallProductInfoList(new MallProductInfo());
        if (mallProductInfos == null || mallProductInfos.size() == 0) {
            log.info("暂无需要同步的商品");
        }
        //调用ES查询索引是否存在
        R<Boolean> indexExit = remoteEsIndexService.indexExit("mall_product");
        if (!indexExit.getData()) {
            log.info("mall_product索引不存在,调用ES服务创建索引");
            //创建索引
            R<Boolean> indexCreate = remoteEsIndexService.indexCreate("mall_product");
            if (!indexCreate.getData()) {
                log.info("创建mall_product索引失败");
            }
            //批量同步商品信息到ES
            //构建参数
            List<EsDocInsertVo> esDocInsertVo = builderProductInfoToEs(mallProductInfos);
            //调用ES服务批量插入文档
            R<Boolean> batchInsert = remoteEsDocService.batchInsertDocs(esDocInsertVo);
            if (batchInsert.getData()) {
                log.info("批量同步商品信息到ES成功");
            }

        }

    }

    @Override
//    @Transactional(rollbackFor = Exception.class)
    public void updateMallProductInfoById(Long id, Integer infoStatus) {
        if(id==null){
            throw new RuntimeException("商品id不能为空");
        }
        //TODO 查询商品信息
        ProductModel productModel = mallProductInfoMapper.selectProductModelById(id);
        if (productModel == null) {
            throw new RuntimeException("商品信息不存在");
        }
        //TODO 查询商品SKU信息
        List<MallProductSkuInfo> mallProductSkuInfos = skuInfoMapper.selectMallProductSkuInfoByProductId(id);
        if(CollectionUtils.isEmpty(mallProductSkuInfos)){
            throw new RuntimeException("该商品id下不存在sku信息");
        }
        Integer flag = mallProductInfoMapper.updateMallProductInfoById(id, infoStatus);
        if(flag<=0){
            throw new RuntimeException("上下架失败");
        }
//        try {
//            int i=1/0;
//        }catch (Exception e){
//            throw new RuntimeException("错误");
//        }
        //TODO 判断商品上下架状态
        if(infoStatus==1){
            //远程调用es添加
            try {
                //参数转换
                List<EsDocInsertVo> esDocInsertVos=transForData(productModel,mallProductSkuInfos);
                remoteEsDocService.batch(esDocInsertVos);
            }catch (Exception e){
                throw new RuntimeException("远程调用es上架失败"+e);
            }
        }
        if(infoStatus==0){
            //远程调用es删除
            for (MallProductSkuInfo mallProductSkuInfo : mallProductSkuInfos) {
                try {
                    remoteEsDocService.del(INDEX_NAME,mallProductSkuInfo.getId());
                }catch (Exception e){
                    throw new RuntimeException("远程调用es下架失败");
                }
            }
        }
    }

    private List<EsDocInsertVo> transForData(ProductModel productModel, List<MallProductSkuInfo> mallProductSkuInfos) {
        remoteEsIndexService.indexCreate(INDEX_NAME);
        //构建返回结果集
        List<EsDocInsertVo> esDocInsertVos = new ArrayList<>();
        mallProductSkuInfos.stream().forEach(mallProductInfo -> {
            EsDocInsertVo esDocInsertVo = new EsDocInsertVo();
            esDocInsertVo.setId(String.valueOf(mallProductInfo.getId()));
            esDocInsertVo.setIndexName(INDEX_NAME);
        //对象转为Map
            Map<String, Object> map = JSON.parseObject(JSON.toJSONString(productModel), Map.class);
            map.put("productName",productModel.getName());
            map.put("title",productModel.getBrandName());
            map.put("desc",productModel.getProductDesc());
            map.put("keywords",productModel.getKeywords());
            List<String> suggestions = esDocInsertVo.getSuggestions();
            if (suggestions == null) {
                 suggestions= new ArrayList<>();
            }
            suggestions.add(productModel.getProductDesc());
            suggestions.add(productModel.getKeywords());
            suggestions.add(productModel.getName());
            map.put("suggestions",suggestions);
            if(StringUtils.isNotBlank(productModel.getCarouselImages())){
                mallProductInfo.setImages(Arrays.asList(productModel.getCarouselImages().split(",")));
            }
            map.put("images",mallProductInfo.getImages());
            if(productModel.getType()!=null){
                map.put("type",productModel.getType());
                map.put("typeName",mallProductTypeInfoMapper.selectMallProductTypeInfoById(Long.valueOf(productModel.getType())).getName());
            }
            esDocInsertVo.setData(map);
            esDocInsertVos.add(esDocInsertVo);
        });
        return esDocInsertVos;
    }



    private List<EsDocInsertVo> builderProductInfoToEs(List<MallProductInfo> mallProductInfos) {
        List<EsDocInsertVo> esDocInsertVos = new ArrayList<>();
        mallProductInfos.stream().forEach(mallProductInfo -> {
            EsDocInsertVo esDocInsertVo = new EsDocInsertVo();
            esDocInsertVo.setId(String.valueOf(mallProductInfo.getId()));
            esDocInsertVo.setIndexName("mall_product");
            //对象转为Map
            Map<String, Object> data = JSON.parseObject(JSON.toJSONString(mallProductInfo), Map.class);
            esDocInsertVo.setData(data);
            esDocInsertVos.add(esDocInsertVo);
        });
        return esDocInsertVos;
    }

}
